﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using OfficeOpenXml.FormulaParsing.Logging;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// WMS硅料AB料转换查询匹配处理接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ABBarCodeChangeController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_qh;
        public readonly string con_yb;
        public readonly string con_t;


        public ABBarCodeChangeController(ILogger<ABBarCodeChangeRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_t = _configuration.GetConnectionString("WMSDbConnection_Test");
            _logger = loggerFactory.CreateLogger<ABBarCodeChangeController>();

        }

        /// <summary>
        /// WMS硅料AB料转换查询匹配处理接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostABChange([FromBody] ABBarCodeChangeRequestDto strparm)
        {
            string  strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            ABBarCodeChangeResponseDto re = new ABBarCodeChangeResponseDto();


            if (strparm.factory_code.Trim() == "" || strparm.factory_code.Trim() == null)
            {
                strMsg = "基地编码不能为空，处理失败！";
            }
            if (strparm.change_type.Trim() == "" || strparm.change_type.Trim() == null)
            {
                strMsg = "接口处理类型不能为空,只能等于<select>、<fine>、<submit>！";
            }
            if (strparm.material_code.Trim() == "" || strparm.material_code.Trim() == null)
            {
                strMsg = "来源物料编码不能为空，处理失败！";
            }
            if (strparm.source_batch.Trim() == "" || strparm.source_batch.Trim() == null)
            {
                strMsg = "来源批次号不能为空，处理失败！";
            }
            if (strparm.source_no.Trim() == "" || strparm.source_no.Trim() == null)
            {
                strMsg = "来源单据号不能为空，处理失败！";
            }
            if (strparm.packing_size.Trim() == "" || strparm.packing_size.Trim() == null)
            {
                strMsg = "包装规格不能为空，处理失败！";
            }
            if (strparm.material_code_t.Trim() == "" || strparm.material_code_t.Trim() == null)
            {
                strMsg = "目标物料编码不能为空，处理失败！";
            }
            if (strparm.source_batch_t.Trim() == "" || strparm.source_batch_t.Trim() == null)
            {
                strMsg = "目标批次不能为空，处理失败！";
            }



            string strcon = "";
            if (strparm.factory_code == "yb")
            {
                strcon = con_yb;
            }
            else if (strparm.factory_code == "qh")
            {
                strcon = con_qh;
            }
            else if (strparm.factory_code == "ts")
            {
                strcon = con_t;
            }
            else
            {

            }

            if (strcon == "")
            {
                strMsg = "所属基地=<" + strparm.factory_code + ">只能等于yb=宜宾高景、qh=青海高景，处理失败！";
            }


            try
            {
                if (strMsg == "")
                {
                    dic = new Dictionary<string, string>(); //校验当前来源单号是否已提交
                    dic.Add("source_no", strparm.source_no);
                    DataTable c_sor = MethodHelp.GetOutsideTableInfo("TMS0239", dic, strcon, con);
                    if (c_sor.Rows.Count>0)
                    {
                        strMsg = "所属基地=<" + strparm.factory_code + ">,来源单据号=<" + strparm.source_no + ">已存在提交记录，请确认后再试！";
                    }
                    else
                    {
                        if (strparm.change_type == "select")
                        {
                            dic = new Dictionary<string, string>(); //查询是否存在满足条码件来源条码明细
                            dic.Add("material_code", strparm.material_code);
                            dic.Add("source_batch", strparm.source_batch);
                            dic.Add("material_amount", strparm.packing_size);
                            DataTable c_barcode = MethodHelp.GetOutsideTableInfo("TMS0232", dic, strcon, con);
                            if (c_barcode.Rows.Count > 0)
                            {
                                string material_name_target = "";
                                dic = new Dictionary<string, string>(); //查询是否存在满足条码件来源条码明细
                                dic.Add("material_code", strparm.material_code_t);
                                DataTable mt_dt= MethodHelp.GetOutsideTableInfo("TMS0240", dic, strcon, con);
                                if (mt_dt.Rows.Count>0)
                                {
                                    material_name_target = mt_dt.Rows[0]["material_name"].ToString();
                                }


                                //插入查询结果，待匹配数据条码对照表
                                dic = new Dictionary<string, string>();
                                dic.Add("material_code", strparm.material_code);
                                dic.Add("source_batch", strparm.source_batch);
                                dic.Add("material_amount", strparm.packing_size);
                                dic.Add("material_code_target", strparm.material_code_t);
                                dic.Add("material_name_target", material_name_target);
                                dic.Add("target_batch", strparm.source_batch_t);
                                dic.Add("source_no", strparm.source_no);
                                dic.Add("user_name", strparm.create_user);
                                strMsg = MethodHelp.InsertOutsideIntoTable("TMS0233", dic, strcon, con);


                                dic = new Dictionary<string, string>(); //查询是否存在满足条码件来源条码明细
                                dic.Add("source_no", strparm.source_no);
                                DataTable c_o_barcode = MethodHelp.GetOutsideTableInfo("TMS0234", dic, strcon, con);
                                if (c_o_barcode.Rows.Count > 0)
                                {
                                    re.data = DB.TableToListModel<ABBarCodeChangeResponseData>(c_o_barcode);
                                }
                            }
                            else
                            {
                                strMsg = "所属基地=<" + strparm.factory_code + ">,物料编码_来源=<" + strparm.material_code + ">,批次号_来源=<" + strparm.source_batch + ">,包装规格=<" + strparm.packing_size + ">,锁定在匹配表(查询报表确认)或找不到来源条码数据，请确认后再试！";
                            }

                        }
                        else if (strparm.change_type == "fine")
                        {
                            dic = new Dictionary<string, string>(); //查询是否存在满足条码件来源条码明细
                            dic.Add("source_no", strparm.source_no);
                            DataTable c_o_barcode = MethodHelp.GetOutsideTableInfo("TMS0234", dic, strcon, con);
                            if (c_o_barcode.Rows.Count > 0)
                            {
                                dic = new Dictionary<string, string>(); //查询是否存在目标
                                dic.Add("material_code", strparm.material_code_t);
                                dic.Add("source_batch", strparm.source_batch_t);
                                dic.Add("material_amount", strparm.packing_size);
                                DataTable c_barcode_t = MethodHelp.GetOutsideTableInfo("TMS0232", dic, strcon, con);
                                if (c_barcode_t.Rows.Count > 0)
                                {
                                    dic = new Dictionary<string, string>();
                                    dic.Add("material_amount", strparm.packing_size);
                                    dic.Add("material_code_target", strparm.material_code_t);
                                    dic.Add("target_batch", strparm.source_batch_t);
                                    dic.Add("source_no", strparm.source_no);
                                    dic.Add("user_name", strparm.create_user);
                                    strMsg = MethodHelp.InsertOutsideIntoTable("TMS0235", dic, strcon, con);

                                    if (strMsg == "")
                                    {
                                        foreach (DataRow item in c_o_barcode.Rows)
                                        {
                                            dic = new Dictionary<string, string>(); //查询是否存在目标
                                            dic.Add("source_no", strparm.source_no);
                                            dic.Add("material_code_target", strparm.material_code_t);
                                            dic.Add("target_batch", strparm.source_batch_t);
                                            dic.Add("material_amount", strparm.packing_size);
                                            DataTable c_barcode_f = MethodHelp.GetOutsideTableInfo("TMS0236", dic, strcon, con);
                                            if (c_barcode_f.Rows.Count > 0)
                                            {
                                                dic = new Dictionary<string, string>(); //查询是否存在目标
                                                dic.Add("source_no", strparm.source_no);
                                                dic.Add("barcode_no_target", c_barcode_f.Rows[0]["barcode_no_target"].ToString());
                                                dic.Add("barcode_no_source", item["barcode_no_source"].ToString());
                                                strMsg = MethodHelp.InsertOutsideIntoTable("TMS0237", dic, strcon, con);
                                            }
                                        }

                                        dic = new Dictionary<string, string>(); //查询是否存在满足条码件来源条码明细
                                        dic.Add("source_no", strparm.source_no);
                                        DataTable c_o_barcode_f = MethodHelp.GetOutsideTableInfo("TMS0234", dic, strcon, con);
                                        if (c_o_barcode_f.Rows.Count > 0)
                                        {
                                            re.data = DB.TableToListModel<ABBarCodeChangeResponseData>(c_o_barcode_f);
                                        }
                                    }

                                }
                                else
                                {
                                    strMsg = "所属基地=<" + strparm.factory_code + ">,物料编码_目标=<" + strparm.material_code + ">,批次号_目标=<" + strparm.source_batch + ">,包装规格=<" + strparm.packing_size + ">,锁定在匹配表(查询报表确认)或找不到来源条码数据，请确认后再试！";
                                }


                            }
                        }
                        else if (strparm.change_type == "submit")
                        {
                            dic = new Dictionary<string, string>(); //查询是否存在满足条码件来源条码明细
                            dic.Add("source_no", strparm.source_no);
                            DataTable check_dt = MethodHelp.GetOutsideTableInfo("TMS0241", dic, strcon, con);
                            if (check_dt.Rows.Count>0)
                            {
                                strMsg = "当前提交数据，存在重复提交数据，来源条码号=<"+ check_dt.Rows[0]["barcode_no_source"].ToString() + ">，目标条码号=<"+ check_dt.Rows[0]["barcode_no_target"].ToString() + ">";
                            }
                            else
                            {
                                strMsg = MethodHelp.InsertOutsideIntoTable("TMS0238", dic, strcon, con);
                            }
                           
                        }
                        else
                        {
                            strMsg = "操作类型=<" + strparm.change_type + ">不存在，值只能等于<select>查询、<fine>匹配、<submit>提交！";
                        }
                    }

                   
                }

            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }




            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }





    }
}
